/**
 * 主界面模块
 */
var App = function () {
    var $body = $(document.body);
    var $center = $('.center-panel');
    var $west = $('.west-panel');
    var $tree = $west.find('.jxtree');
    var $navHome = $('#nav_home');
    var $navLogout = $('#nav_logout');
    var $menuFilter = $tree.parent().find('.jxtree-filter');
    var indexMap, idMap, mindex, mid;

    /**
     * 初始化导航菜单
     */
    var initTree = function () {
        var treeOps = {
            defaultIconCls: 'icon-flag',
            maskMsg: $tree.data('maskMsg') || '正在加载菜单...',
            onLoadSuccess: function (parentNode, result) {
                indexMap = [];
                idMap = [];
                mindex = 0;
                jx.treeRecursion(result, function (n) {
                    mindex = mindex + 1;
                    mid = n.id;
                    indexMap[mindex] = mid;
                    idMap[mid] = mindex;
                });

                var hashId = window.location.hash.replace('#', '');
                if (!hashId) {
                    loadHome();
                    return;
                }

                var nodeId = indexMap[hashId];
                if (!nodeId) {
                    loadHome();
                    return;
                }
                var node = $(this).tree('find', nodeId);
                if (!node) return;
                $(this).tree('expandTo', node.target);
                $(this).tree('select', node.target);
                loadPage(node.url, node.text);
            },
            onClick: function (node) {
                $(this).tree('expand', node.target);
                loadPage(node.url, node.text);
                var hashId = idMap[node.id];
                if (hashId) {
                    window.location.hash = hashId;
                }
            },
            onDblClick: function (node) {
                if (node.state === 'open') {
                    $(this).tree('collapse', node.target);
                }
            },
            onContextMenu: function (e, node) {
                $(this).tree('select', node.target);
                e.preventDefault();
            }
        };
        if ($menuFilter.length > 0) {
            treeOps.filterBox = $menuFilter;
        }
        $tree.options(treeOps);
    };

    /**
     * 初始化主布局
     */
    var initLayout = function () {
        jx.complete(function () {
            $body.jxlayout().monitor('west', 'spring-boot-webapp');

            fullPage(!jx.toBoolean(localStorage.getItem('appPageFull')));
        });
    };

    /**
     * 初始化导航按钮
     */
    var initNav = function () {
        $navHome.on('click', function () {
            window.location.hash = '';
            loadHome();
        });

        $navLogout.on('click', function () {
            var url = $(this).data('url');
            layer.confirm('注：您确定要安全退出本次登录吗？', {icon: 0, title: '系统提示', skin: 'jxnav-layer'}, function (index) {
                $.ajax({
                    url: url,
                    type: 'post',
                    dataType: 'json',
                    data: {}
                }).done(function (result) {
                    layer.close(index);
                    if (result.success) {
                        window.location.href = result.data.url;
                    } else {
                        layer.alert(result.msg);
                    }
                }).fail(function (request) {
                    if (request.responseJSON) {
                        layer.alert(request.responseJSON.message || '退出失败');
                    }
                    else {
                        layer.alert(request.statusText || '退出失败');
                    }
                });
            });
        });


        $('#nav_fullscreen').click(function () {
            toggleFullScreen();
            var isFull = $body.data('appScreenFull');//全屏状态
            $(this).find('span').text(isFull ? '全屏' : '退出全屏');
        });
    };

    /**
     * 初始化用户消息刷新
     */
    var initMessageRefresh = function () {
        var load = function () {
            jx.ajax({
                url: jx.apiUrl('/auth/message/uncount'),
                type: 'post',
                silent: true, //不弹出错误框
                success: function (result) {
                    if (result.success) {
                        var count = result.data.count;
                        if (count > 0) {
                            $('#user_message .icon-bubbles').jxflash();
                            $('#unMessageCountBadge').show().text(count);
                        } else {
                            $('#user_message .icon-bubbles').jxunflash();
                            $('#unMessageCountBadge').hide().text('');
                        }
                    }
                }
            });
        };
        load();//先执行一次查询
        jx.auth.autoTask(load, 20000);//自动刷新任务
    };

    /**
     * 初始化用户激活心跳
     */
    var initOnlineUserRefresh = function () {
        var load = function () {
            jx.ajax({
                url: jx.apiUrl('/auth/onlineuser/active'),
                type: 'post',
                silent: true //不弹出错误框
            });
        };
        jx.auth.autoTask(load, 10000);//自动任务
    };

    /**
     * 初始化刷新当前时间
     */
    var initCurrentDateTimeRefresh = function () {
        var load = function () {
            $('#current_time').text(jx.formatDateTime(new Date()));
        };
        jx.auth.autoTask(load, 1000);//自动任务
    };
    /**
     * 加载主页
     */
    var loadHome = function () {
        var url = $center.data('url');
        var title = '主页';
        loadPage(url, title);
    };

    /**
     * 加载页面
     * @param title 标题
     * @param url Url
     */
    var loadPage = function (url, title) {
        if (!url || url === '#') return;
        url = jx.apiUrl(url);
        var centerPanel = $body.layout('panel', 'center');
        var _url = url + ((/\?/).test(url) ? '&' : '?') + '_ts=' + (Date.now());
        var _title = title || centerPanel.title || '';
        centerPanel.panel({
            title: null,
            content: jx.createIframe(_url)
        });

        centerPanel.mask('正在加载 <span style="color: red;font-weight: bold;">' + _title + '</span> 请稍等...', 500);
        centerPanel.find('iframe').on('load', function () {
            centerPanel.unmask();
        });
    };

    /**
     * 切换中间页面全屏
     */
    var toggleFullPage = function () {
        var isScreenFull = $body.data('appPageFull');//全屏状态
        fullPage(isScreenFull);
        localStorage.setItem('appPageFull', !isScreenFull);
    };

    var fullPage = function (isFull) {
        if (jx.isUndefined(isFull)) isFull = false;
        var panels = $body.data().layout.panels;//全部面板
        var method = isFull === true ? 'open' : 'close';//调用方法

        if (panels.north.length > 0 && panels.north.panel('options').collapsed) panels.expandNorth.panel(method); else panels.north.panel(method);
        if (panels.south.length > 0 && panels.south.panel('options').collapsed) panels.expandSouth.panel(method); else panels.south.panel(method);
        if (panels.east.length > 0 && panels.east.panel('options').collapsed) panels.expandEast.panel(method); else panels.east.panel(method);
        if (panels.west.length > 0 && panels.west.panel('options').collapsed) panels.expandWest.panel(method); else panels.west.panel(method);

        $body.data('appPageFull', !isFull);
        $body.layout('resize');
    };

    /**
     * 切换浏览器全屏
     */
    var toggleFullScreen = function () {
        var isFull = $body.data('appScreenFull');//全屏状态
        fullScreen(isFull);
    };

    /**
     * 浏览器全屏
     */
    var fullScreen = function (isFull) {
        if (jx.isUndefined(isFull)) isFull = true;
        if (isFull === true) {
            var docElm = document.documentElement;
            if (docElm.requestFullscreen) {
                docElm.requestFullscreen();
            }
            else if (docElm.msRequestFullscreen) {
                docElm = document.body; //overwrite the element (for IE)
                docElm.msRequestFullscreen();
            }
            else if (docElm.mozRequestFullScreen) {
                docElm.mozRequestFullScreen();
            }
            else if (docElm.webkitRequestFullScreen) {
                docElm.webkitRequestFullScreen();
            }
        }
        else {
            if (document.exitFullscreen) {
                document.exitFullscreen();
            }
            else if (document.msExitFullscreen) {
                document.msExitFullscreen();
            }
            else if (document.mozCancelFullScreen) {
                document.mozCancelFullScreen();
            }
            else if (document.webkitCancelFullScreen) {
                document.webkitCancelFullScreen();
            }
        }
        $body.data('appScreenFull', !isFull);
    };

    /**
     * 应用程序初始化
     */
    var init = function () {
        initCurrentDateTimeRefresh();
        initTree();
        initLayout();
        initNav();
        initMessageRefresh();
        initOnlineUserRefresh();
    }();

    return {
        /**
         * 加载页面
         * @param url Url
         * @param title 标题
         */
        loadPage: function (url, title) {
            loadPage(url, title);
        },

        /**
         * 中间页面全屏
         */
        toggleFullPage: function () {
            toggleFullPage();
        },
        toggleFullScreen: function () {
            toggleFullScreen();
        },
        fullPage: function (isFull) {
            fullPage(isFull);
        },
        fullScreen: function (isFull) {
            fullScreen(isFull);
        }
    }
};

jx.ready(function () {
    window.app = App();
});